/*
--------------------------------------------------------------------------------
				Ak-Lib. 
			 Project       	: Ak-Lib
			 Group         	: Ak-Lib R&D Team
			 Author        	: Ocean.Wang
			 Create Date 	: 05-01-2010
--------------------------------------------------------------------------------
Code Name 	:  A.K 	~v~
Description	:  Yet Another Cross-Platform Lib.
Cautions    	:
--------------------------------------------------------------------------------
Change History:
Version		: 0.1
Building 		: 05/01/10
10-05.01 first draft, build, debug and test.
--------------------------------------------------------------------------------
*/

#include "ak_gears.h"

static 	int 	_gTraceLvl_SysL = TRACELVL_WARNING;

/* -----------------------------------------------------------------------
** 	Basic Pangolin Instance Check:
**	Make Sure only 1 Instance Run in the System.
*/
#include <sys/shm.h>
#include <sys/stat.h>
int 	Sys_ChkInst(char * shmName)
{
	#define  _CHKINST_PROC_NAME_MAX 	31
	
	int  	shmId, ret, len;
	pid_t * pProc;
	pid_t 	procId;
	key_t 	key;
	struct stat			fStat;
	char 	procName[_CHKINST_PROC_NAME_MAX+1];

	if(shmName){
		len = strlen(shmName);
		/* Check Share Mem, Get the Last Active Process */
		key 		= 	ftok(shmName, 'y');
		shmId 		= 	shmget(key,4096,IPC_CREAT|0666);
		if(shmId == -1){
			SYS_TRACE(_gTraceLvl_SysL, TRACELVL_ERROR, "Cannot Access Share Mem [%d - %d], Prog Exit %d.\n", key, shmId, errno);
			return -1;
		}
		pProc		=	(pid_t *)shmat(shmId,NULL,0);

		if(pProc == (pid_t *)-1){
			SYS_TRACE(_gTraceLvl_SysL, TRACELVL_ERROR, "Cannot Access Share Mem [%d - %d], Prog Exit %d.\n", key, shmId, errno);
			return -1;
		}
		
		procId	 	= 	*pProc;
		ret = SYS_SNPRINTF(procName,_CHKINST_PROC_NAME_MAX, "/proc/%u", procId);
		procName[ret]='\0';
		
		/* Let's Stat It */
		ret	= stat(procName, &fStat);
		
		SYS_TRACE(_gTraceLvl_SysL, TRACELVL_WARNING, "SHM CHK:[%s] -- [%d - %d]\n", procName, ret, errno);
		if((ret == -1) && (errno == ENOENT)){
			/* Update the Share Mem */
			procId = getpid();
			*pProc = procId;
			shmdt(pProc);
			return 0;
		}
	}
	return -1;
	
}


